package cn.zhz.controller.develop;

import cn.zhz.pojo.DevUser;
import cn.zhz.service.devuser.DevUserService;
import cn.zhz.tools.Constants;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/dev")
public class DevUserController {
    @Resource
    private DevUserService service;
    private Logger logger = Logger.getLogger(DevUserController.class);

    @RequestMapping(value = "/login")
    public String login() {
        logger.debug("============login loading=============");
        return "devlogin";
    }

    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    public String doLogin(@RequestParam String devCode, @RequestParam String devPassword,
                          HttpSession session, HttpServletRequest request) {
        logger.debug("============doLogin=============");

        DevUser user = null;
        try {
            user = service.login(devCode, devPassword);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != user) {
            session.setAttribute(Constants.DEV_USER_SESSION, user);
            return "redirect:/dev/flatform/main";
        } else {
            request.setAttribute("error", "用户名或者密码不正确");
            return "devlogin";
        }

    }

    @RequestMapping(value = "/flatform/main")
    public String main(HttpSession session) {
        if (session.getAttribute(Constants.DEV_USER_SESSION) == null) {
            return "redirect:/dev/login";
        }
        return "developer/main";
    }

    @RequestMapping(value = "logout")
    public String logout(HttpSession session) {
        //清除session
        session.removeAttribute(Constants.DEV_USER_SESSION);
        return "devlogin";
    }
}
